﻿using Microsoft.AspNetCore.Http;
using Shop.Application.Common;
using Shop.Application.Orders.Dto;
using Shop.DB;
using Shop.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Shop.Application.Orders
{
    public class CreateOrder
    {
        private DBContext _context;
        private ISession _session;

        public CreateOrder(DBContext context, ISession session)
        {
            _context = context;
            _session = session;
        }

        public async Task<bool> Do(OrderInput input)
        {
            var stockHolds = _context.StockHolds.Where(x => x.SessionID == _session.Id).ToList();
            _context.RemoveRange(stockHolds);
            var order = new Order
            {
                StripeRefer = input.StripeRefer,
                OrderName = DateTime.Now.ToString("yyyyMMdd") + CreateName.CreateOrderName(_context,6),
                UserName = input.UserName,
                Email = input.Email,
                PhoneNumber = input.PhoneNumber,
                Address = input.Address,
                City = input.City,
                PostCode = input.PostCode,
                OrderStocks = input.OrderStocks.Select(x => new OrderStock
                {
                    StockID = x.StockID,
                    Count = x.Count
                }).ToList()
            };
            order.OrderStocks.Select(x => x.OrderID = order.OrderID).ToList();
            _context.Orders.Add(order);
            return await _context.SaveChangesAsync() > 0;
        }
    }
}
